package com.aerozhonghuan.logisticsmall.modules.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aerozhonghuan.foundation.base.BaseFragment;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.modules.common.event.HaveUnreadMessageEvent;
import com.aerozhonghuan.logisticsmall.modules.common.event.UserInfoChangedSuccessEvent;
import com.aerozhonghuan.logisticsmall.modules.mine.activity.FeedBackAcrivity;
import com.aerozhonghuan.logisticsmall.modules.mine.activity.MessageAcrivity;
import com.aerozhonghuan.logisticsmall.modules.mine.activity.SettingAcrivity;
import com.aerozhonghuan.logisticsmall.modules.mine.activity.UserinfoAcrivity;
import com.aerozhonghuan.logisticsmall.modules.mine.adapter.RowItemAdapter;
import com.aerozhonghuan.logisticsmall.modules.mine.beans.MenuItem;
import com.aerozhonghuan.logisticsmall.modules.order.MyOrdersAcrivity;
import com.aerozhonghuan.logisticsmall.modules.order.OrderSettlementAcrivity;
import com.aerozhonghuan.logisticsmall.modules.order.logic.OrderStateControl;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserBean;
import com.aerozhonghuan.logisticsmall.modules.user.logic.UserInfoManager;
import com.aerozhonghuan.logisticsmall.widget.TitleBarView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


/**
 * 描述:我的
 * 作者:zhangyonghui
 * 创建日期：2017/6/20 0020 on 上午 11:28
 */

public class MineFragment extends BaseFragment {
    private static final String TAG = "MineFragment";
    public static final String MENU_ITEM_SETTING = "设置";
    public static final String MENU_ITEM_FEEDBACK = "意见反馈";
    private View rootView;
    private ViewGroup section1;
    private TextView tv_name;
    private TextView tv_company;
    private TitleBarView titleBar;
    private View viewUnreadMark;
    private LinearLayout llOrderstate;
    private LayoutInflater layoutInflater;
    private OnItemClick mOnItemClick = new OnItemClick() {
        @Override
        public void onItemClick(String title) {
            if (MENU_ITEM_SETTING.equals(title)) {
                startActivity(new Intent(getContext(), SettingAcrivity.class));
            } else if (MENU_ITEM_FEEDBACK.equals(title)) {
                startActivity(new Intent(getContext(), FeedBackAcrivity.class));
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusManager.register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.mine_fragment, null);
            initView();
            initData();

        }
        return rootView;
    }

    private void initView() {
        layoutInflater = LayoutInflater.from(getContext());
        titleBar = (TitleBarView) rootView.findViewById(R.id.titlebarview1);
        titleBar.enableBackButton(false);
        titleBar.setTitle(getResources().getString(R.string.string_tab_mine));
        section1 = (ViewGroup) rootView.findViewById(R.id.section1);
        llOrderstate = (LinearLayout) rootView.findViewById(R.id.ll_orderstate);
        viewUnreadMark = rootView.findViewById(R.id.view_unreadmark);
        rootView.findViewById(R.id.tv_ordersettlement).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), OrderSettlementAcrivity.class));
            }
        });
        rootView.findViewById(R.id.rel_myorders).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MyOrdersAcrivity.class));
            }
        });
        rootView.findViewById(R.id.rel_message).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewUnreadMark.setVisibility(View.GONE);
                goMessagePage();
            }
        });
        rootView.findViewById(R.id.rel_userinfo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goUserInfoPage();
            }
        });
        tv_name = (TextView) rootView.findViewById(R.id.tv_name);
        tv_company = (TextView) rootView.findViewById(R.id.tv_company);
        buildSectionViews();
        initOrderStateView();
    }

    private void initOrderStateView() {
        LinearLayout.LayoutParams topContentTextView_lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        for (int i = 0; i < OrderStateControl.orderStates.size(); i++) {
            final int position = i;
            View view = layoutInflater.inflate(R.layout.item_mine_orderstate, null);
            ImageView imgState = (ImageView) view.findViewById(R.id.img_state);
            TextView tvState = (TextView) view.findViewById(R.id.tv_state);
            imgState.setImageResource(OrderStateControl.orderStates.get(position).iconId);
            tvState.setText(OrderStateControl.orderStates.get(position).name);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(getActivity(), MyOrdersAcrivity.class).putExtra(MyOrdersAcrivity.KEY_POSITION, position));
                }
            });
            llOrderstate.addView(view, topContentTextView_lp);
        }
    }

    private void initData() {
        UserBean userbean = UserInfoManager.getCurrentUserDetailInfo();
        if (userbean != null) {
            if (!TextUtils.isEmpty(userbean.getNickname())) {
                tv_name.setText(userbean.getNickname());
            } else {
                tv_name.setText("未设置");
            }
            if (userbean.getCompany() != null && !TextUtils.isEmpty(userbean.getCompany().getName())) {
                tv_company.setText(userbean.getCompany().getName());
            } else {
                tv_company.setText("未设置");
            }
        }
    }

    /**
     * 跳转到用户信息页
     */
    private void goUserInfoPage() {
        startActivity(new Intent(getActivity(), UserinfoAcrivity.class));
    }

    /**
     * 跳转到消息页面
     */
    private void goMessagePage() {
        startActivity(new Intent(getActivity(), MessageAcrivity.class));
    }

    /**
     * 存在未读消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(HaveUnreadMessageEvent haveUnreadMessageEvent) {
        if (getActivity().isFinishing()) {
            return;
        }
        viewUnreadMark.setVisibility(View.VISIBLE);
    }

    /**
     * 用户信息发生改变
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(UserInfoChangedSuccessEvent e) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        LogUtil.d(TAG, "收到事件: 用户信息发生改变");
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusManager.unregister(this);
    }

    private void buildSectionViews() {
        if (getContext() == null) {
            throw new NullPointerException();
        }
        ArrayList<MenuItem> sectionList1 = new ArrayList<>();
        sectionList1.add(new MenuItem(R.mipmap.ic_feedback, MENU_ITEM_FEEDBACK, ""));
        sectionList1.add(new MenuItem(R.mipmap.ic_setting, MENU_ITEM_SETTING, ""));
        RowItemAdapter adapter1 = new RowItemAdapter(sectionList1, getContext());
        for (int i = 0; i < adapter1.getCount(); i++) {
            View convertView = null;
            convertView = adapter1.getView(i, convertView, null);
            section1.addView(convertView);
            View line = layoutInflater.inflate(R.layout.split_line, null);
            if (adapter1.getCount() > 1 && i < adapter1.getCount() - 1) {
                section1.addView(line);
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() != null && v.getTag() instanceof RowItemAdapter.ViewHolder) {
                        RowItemAdapter.ViewHolder viewHolder = (RowItemAdapter.ViewHolder) v.getTag();
                        if (mOnItemClick != null) {
                            mOnItemClick.onItemClick(viewHolder.textViewTitle.getText().toString());
                        }
                    }
                }
            });
        }
    }

    private interface OnItemClick {
        void onItemClick(String title);
    }
}
